package cn.seaboot.admin.mvc.mask;

import cn.seaboot.commons.reflect.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.*;

/**
 * 数据脱敏总控制器
 * <p>
 * 函数返回值数据脱敏
 *
 * @see cn.seaboot.admin.mvc.response.ControllerDesensitizationExample
 * @see cn.seaboot.admin.mybatis.MybatisStarter
 * @author Mr.css
 * @version 2023-06-29 14:31
 */
@Configuration
public class ReturnValueDesensitization {

    /**
     * 默认数据脱敏工具
     */
    private final ObjectDesensitization defaultDesensitization = new DefaultDesensitization();

    /**
     * 数据脱敏工具池
     */
    private final Map<Class<?>, ObjectDesensitization> desensitizationMap = new HashMap<>();

    /**
     * 数据脱敏工具池
     *
     * @param clazz           对象
     * @param desensitization 脱敏工具
     */
    public void register(Class<?> clazz, ObjectDesensitization desensitization) {
        desensitizationMap.put(clazz, desensitization);
    }

    /**
     * 函数返回值是否需要脱敏
     *
     * @param method 函数
     * @return ret
     */
    public boolean supports(@NotNull Method method) {
        return method.getAnnotation(Desensitize.class) != null;
    }

    /**
     * 处理数据脱敏
     *
     * @param o 需要脱敏的数据，可能是 list/array
     */
    public void process(Object o) {
        if (o != null) {
            Class<?> clazz = o.getClass();
            if (!Map.class.isAssignableFrom(clazz)) {
                // ignore
                return;
            }
            if (Collection.class.isAssignableFrom(clazz)) {
                // collection
                Collection<?> list = (Collection<?>) o;
                if (!list.isEmpty()) {
                    Class<?> type = ObjectUtils.getCollectionGeneric(list);
                    ObjectDesensitization desensitization = getDesensitization(type);
                    for (Object obj : list) {
                        desensitization.process(obj);
                    }
                }
            } else if (clazz.isArray()) {
                // array
                int len = Array.getLength(o);
                if (len > 0) {
                    Class<?> type = ObjectUtils.getArrayGeneric(o);
                    ObjectDesensitization desensitization = getDesensitization(type);
                    for (int i = 0; i < len; i++) {
                        desensitization.process(Array.get(o, i));
                    }
                }
            } else {
                // standard instance
                getDesensitization(o.getClass()).process(o);
            }
        }
    }

    /**
     * 根据对象类型，确定脱敏工具
     *
     * @param clazz 对象类型
     * @return 脱敏工具实体
     */
    private ObjectDesensitization getDesensitization(Class<?> clazz) {
        ObjectDesensitization ret = desensitizationMap.get(clazz);
        return ret == null ? defaultDesensitization : ret;
    }
}
